package com.king.base.service.log.impl;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.king.base.auth.security.AuthorizationUser;
import com.king.base.domain.log.Log;
import com.king.base.mapper.log.LogMapper;
import com.king.base.service.log.LogService;
import com.king.base.utils.IpUtil;
import com.king.base.utils.RequestHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author Spur
 * @date 2019-10-28
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class LogServiceImpl extends ServiceImpl<LogMapper,Log> implements LogService {
    private final String LOGINPATH = "authenticationLogin";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(ProceedingJoinPoint joinPoint, Log logging){
        // 获取request
        HttpServletRequest request = RequestHolder.getHttpServletRequest();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        com.king.base.aop.Log log = method.getAnnotation(com.king.base.aop.Log.class);
        // 描述
        if (log != null) {
            logging.setDescription(log.description());
        }
        // 方法路径
        String methodName = joinPoint.getTarget().getClass().getName()+"."+signature.getName()+"()";
        String params = "";
        //参数值
        Object[] argValues = joinPoint.getArgs();
        //参数名称
        String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
        // 用户名
        String username = "";
        if(argValues != null){
            for (int i = 0; i < argValues.length; i++) {
                params += " " + argNames[i] + ": " + com.alibaba.fastjson.JSONObject.toJSONString(argValues[i]);
            }
        }
        // 获取IP地址
        logging.setRequestIp(IpUtil.getIP(request));

        if(!LOGINPATH.equals(signature.getName())){
            UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            username = userDetails.getUsername();
        } else {
            AuthorizationUser user = JSONUtil.toBean(new JSONObject(argValues[0]),AuthorizationUser.class);
            username = user.getUsername();
        }
        logging.setRequestMethod(methodName);
        logging.setRequestParam(params + " }");
        logging.setCrtUserName(username);
        logging.setCrtTime(new Date());
        logging.setUpdTime(new Date());
        baseMapper.insert(logging);
    }
    @Override
    public IPage<Log> errorPage(Page page, Log log) {
        return baseMapper.errorPage(page, log);
    }
}
